<template>
  <div class="c-ph24 videoAudio" @click="clickAudioCom">
    <audio id="audioPlayer" class="c-pf c-p-l-100" :title="audioTitle">
      <source id="audioSource" src="" type="audio/mpeg">
    </audio>
    <div class="c-flex-row c-aligni-center">
      <div @click="clickPlay" v-show="playStatus == 0" class="iconfont c-fc-white c-fs24 c-mr32">&#xe728;</div>
      <div @click="clickPlay" v-show="playStatus == 1" class="iconfont c-fc-white c-fs24 c-mr32">&#xe8ef;</div>
      <div class="c-fc-white c-fs20 c-mt5">{{curPlayTimeFomat}}</div>
      <div class="c-flex-grow1 c-w0 c-ph20 c-mt5">
        <vue-slider :height="2" :processStyle="processStyle" :railStyle="railStyle" :dotOptions="dotOptions" v-model="audioPlayTime" tooltip="none" :max="duration" :disabled="!hasPermission" @drag-start="dragStart" @dragging="dragging" @drag-end="dragEnd" @change="inputChange">
        </vue-slider>
      </div>
      <div class="c-fc-white c-fs20 c-mt5">{{durationTimeFomat}}</div>
    </div>
    <wx-open-audio id="audioPlayer" v-if="audioType == 2" :title="audioTitle" :type="isHls" :src="audioSrc" :playbackRate="playbackRate" class="c-ww24 c-hh24 c-pa c-p-t48 c-opacity0"></wx-open-audio>
  </div>
</template>
<script>
import { utilJs } from "@/utils/common.js";
import VueSlider from "vue-slider-component";
import "vue-slider-component/theme/antd.css";
const Hls = require("hls.js");
const IS_IOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
// import SliderCom from "@/components/templates/common/audio/SliderCom.vue";
let playTimeControl = null;
let isFirstPlay = true; //是否第一次赋值src，是的话第一次不播放
let isDeactivated = false; //是否销毁对象，解决销毁了会继续出发audioTimeUpdate 导致audioTime无法为0
let isCanPlay = false; //是否能开始播放音频
let pageStatus = 'visible';
// let isPlaySuccess = 0;
let hiddenPlay = 0;
export default {
  name: "",
  components: {
    VueSlider
  },
  props: {
    playbackRate: {
      type: Number,
      default: 1
    },
    watchTime: { //秒
      type: Number,
      default: 0
    },
    audioTitle: {
      type: String,
      default: "音频详情"
    },
    audioUrl: {
      type: String,
      default: ""
    },
    audioAndSrc: {
      type: String,
      default: ""
    },
    audioIOSSrc: {
      type: String,
      default: ""
    },
    hasPermission: {
      type: Boolean,
      default: false
    },
    curPlayTime: {
      type: Number,
      default: 0
    },
    totalPlayedTime: {
      type: Number,
      default: 0
    },
    showPlayBack: {
      type: Boolean,
      default: false
    },
    hasAuditionPermission: {
      type: Boolean,
      default: false
    },
    miniQr: {
      type: String,
      default: ""
    },
    isCourseChange: { //从音频课程跳转到音频课程的时候，会自动开始播放，所以加上控制
      type: Boolean,
      default: false
    },
    isNeedFirstPlay: { //为true时，第一次赋值src也能播放
      type: Boolean,
      default: false
    },
    isAllowProgressBar: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    curPlayTimeFomat() {
      let minutes = Math.floor(this.audioPlayTime / 60);
      let seconds = Math.floor(this.audioPlayTime % 60);
      minutes = minutes < 10 ? `0${minutes}` : minutes;
      seconds = seconds < 10 ? `0${seconds}` : seconds;
      return `${minutes}:${seconds}`;
    },
    durationTimeFomat() {
      let minutes = Math.floor(this.duration / 60);
      let seconds = Math.floor(this.duration % 60);
      minutes = minutes < 10 ? `0${minutes}` : minutes;
      seconds = seconds < 10 ? `0${seconds}` : seconds;
      return `${minutes}:${seconds}`;
    }
  },
  watch: {
    playbackRate(val, oldVal) {
      document.getElementById('audioPlayer').playbackRate = val;
    },
    isCourseChange: {
      handler(val, oldVal) {
        if (val) {
          // this.playStatus = 0;
          if (this.playStatus == 1) {
            this.audioPause();
          }
          isFirstPlay = true;
        }
      }
    },
    audioUrl: {
      handler(val, oldVal) {
        console.log("newSrc d: %s, oldSrc: %s", val, oldVal);
        if (!val) {
          return;
        }
        document.getElementById('audioPlayer').src = val;
        document.getElementById('audioSource').src = val;
        document.getElementById('audioPlayer').load();
        // isPlaySuccess = 0;
        // if (!isFirstPlay || this.isNeedFirstPlay) {
        //   this.audioPlay();
        // }
      }
    },
    audioAndSrc: {
      handler(val, oldVal) {
        console.log("newSrc d: %s, oldSrc: %s", val, oldVal);
        if (!val || IS_IOS) {
          return;
        }
        document.getElementById('audioPlayer').src = val;
        document.getElementById('audioSource').src = val;
        document.getElementById('audioPlayer').load();
        // isPlaySuccess = 0;
        // if (!isFirstPlay || this.isNeedFirstPlay) {
        //   this.audioPlay();
        // }
        this.isHls = " ";
      }
    },
    audioIOSSrc: {
      handler(val, oldVal) {
        console.log("newSrc d: %s, oldSrc: %s", val, oldVal);
        if (!val || !IS_IOS) {
          return;
        }
        // isPlaySuccess = 0;
        document.getElementById('audioPlayer').src = val;
        document.getElementById('audioSource').src = val;
        document.getElementById('audioPlayer').load();
        this.audioPlayTime = 0;
        // if (!isFirstPlay || this.isNeedFirstPlay) {
        //   this.audioPlay();
        // }
        this.isHls = "hls";
      }
    },
    curPlayTime: {
      handler(val, oldVal) {
        if (!val) {
          return;
        }
        console.log("new d: %s, old: %s", val, oldVal);
        setTimeout(function () {
          document.getElementById('audioPlayer').currentTime = val;
        }, 200)
      }
    }
  },
  data() {
    return {
      menus: {
        1: "倍速选择",
        7: "0.7x",
        10: "1.0x",
        12: "1.2x",
        15: "1.5x",
        20: "2.0x"
      },
      dotOptions: {
        style: {
          border: "1px solid rgba(255,255,255,1)",
          "box-shadow": "0px 2px 5px 0px rgba(0, 0, 0, 0.2)"
        },
        focusStyle: {
          border: "2px solid #389ce7"
        }
      },
      processStyle: {
        "background-color": "#569EF8"
      },
      railStyle: {
        "background-color": "#ededed"
      },
      playStatus: 0, // 播放状态
      duration: 0, //总时长
      // playbackRate: 1, //播放速度
      isAndroidApp: false,
      audioPlayTime: 0,
      maxTime: 100,
      showSpeedModal: false,
      dragFlag: false,
      slideValue: 0, //移动了几步
      isShowMiniQr: false,
      isClicked: false,
      hasWxapp: localStorage.getItem("hasWxapp"),
      ckFrom: this.$route.query.ckFrom,
      isHls: "", //微信开放标签如果是m3u8的话要传type='hls'
      audioSrc: '', // 音频播放路径
      audioType: 2, // 1 原生播放 2 wx浮窗播放
      isClickPause: false, // 手动暂停
    };
  },
  methods: {
    // 处理小程序息屏音频暂停播放的问题
    hiddenPlay() {
      // 小程序环境下 且非手动触发暂停的情况下 且当前播放进度到总进度
      if (this.$isWxApp() && this.isClickPause == false && this.playStatus == 0 && (this.audioPlayTime < this.totalPlayedTime)) {
        this.audioPlay();
        this.playStatus = 1;
      }
    },
    visibilitychange() {
      if (document.visibilityState === 'hidden') {
        console.log('隐藏页面了*******')
        //试听切到后台暂停播放
        if (!this.hasPermission && this.watchTime * 1 > 0) {
          this.audioPause();
        }
        // if (IS_IOS) {
        //   pageStatus = 'hidden';
        //   hiddenPlay = 1;
        // }
        console.log('息屏');
        this.hiddenPlay();
      } else if (document.visibilityState === 'visible' && IS_IOS) {
        console.log('页面显示了*********')
        pageStatus = 'visible';
        //切到前台，获取当前的播放时间，防止播放失败的时候可以回到现在的时间
        if (document.getElementById('audioPlayer') && document.getElementById('audioPlayer').curPlayTime > 0) {
          this.audioPlayTime = document.getElementById('audioPlayer').currentTime;
        }
      }
    },
    clickMenu(menuKey, menuItem) {
      if (menuKey == "cancel") {
        this.showSpeedModal = false;
        return;
      }
      if (menuKey > 2 && menuKey < 30) {
        this.showSpeedModal = false;
        this.playbackRate = menuKey / 10;
        document.getElementById('audioPlayer').playbackRate = menuKey / 10;
      }
    },
    clickAudioCom() {
      this.$emit("clickNoPermission");
    },
    clickBefor() {
      this.$emit("clickBefor");
    },
    onPlay() {
      this.playStatus = 1;
      console.log('播放了*************')
      this.$emit("startPlay", this.playStatus);
    },
    onPause() {
      console.log('暂停了*************')
      this.playStatus = 0;
      clearInterval(playTimeControl);
      //获取当前的播放时间，防止播放失败的时候可以回到现在的时间
      if (IS_IOS && document.getElementById('audioPlayer') && document.getElementById('audioPlayer').currentTime > 0) {
        this.audioPlayTime = document.getElementById('audioPlayer').currentTime;
      }
      this.$emit("audioPause");
    },
    //点击播放/暂停 按钮
    clickPlay() {
      // if ((!this.audioAndSrc && !IS_IOS) || (!this.audioIOSSrc && IS_IOS)) {
      //   return;
      // }
      if (!this.audioUrl) {
        return;
      }
      this.isClicked = true;
      // isPlaySuccess = 1;
      if (this.playStatus == 1) {
        this.audioPause();
        this.isClickPause = true;
      } else {
        this.audioPlay();
        this.isClickPause = false;
      }
    },
    clickAfter() {
      this.$emit("clickAfter");
    },
    clickSpeed() {
      this.showSpeedModal = true;
    },
    //使用hls播放
    playAudioHls(src, hlsStr) {
      let audio = document.getElementById('audioPlayer');
      let audioSource = document.getElementById('audioSource');
      // HLS support ios直播播放m3u8 安卓使用hls播放
      if (!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        audioSource.src = src;
        audio.src = src;
        audio.load();
        this.audioSrc = audioSource.src;
        if (!isFirstPlay || this.isNeedFirstPlay) {
          this.audioPlay();
        }
      } else {
        console.log("不支持支持播放m3u8");
        try {
          if (Hls.isSupported()) {
            if (!this.hls) {
              this.hls = new Hls();
            }
            this.hls.loadSource(src);
            this.hls.attachMedia(audio);
            if (!isFirstPlay || this.isNeedFirstPlay) {
              this.audioPlay();
            }
          } else {
            console.log("HLS is not supported on your browser");
            audioSource.src = src;
            audio.src = src;
            audio.load();
            this.audioSrc = audioSource.src;
            if (!isFirstPlay || this.isNeedFirstPlay) {
              this.audioPlay();
            }
          }
        } catch (e) {
          console.log("hls.js is required to support m3u8");
          audioSource.src = src;
          audio.src = src;
          audio.load();
          this.audioSrc = audioSource.src;
          if (!isFirstPlay || this.isNeedFirstPlay) {
            this.audioPlay();
          }
        }
      }
      this.isHls = hlsStr;
    },
    //播放失败，如果IOS则替换成播放mp4,如果是安卓，则替换成m3u8
    audioError(e) {
      console.log("audioError****");
      console.log(e);
      console.log(document.getElementById('audioPlayer').src);
      console.log(document.getElementById('audioPlayer').currentTime);
      console.log(this.audioIOSSrc);
      console.log("audioErrorEND****");
      // if (isPlaySuccess == 1) {
      //   return;
      // }
      // if (IS_IOS && document.getElementById('audioPlayer').src == this.audioIOSSrc) {
      //   //获取当前的播放时间，防止播放失败的时候可以回到现在的时间
      //   if (IS_IOS && document.getElementById('audioPlayer') && document.getElementById('audioPlayer').currentTime > 0) {
      //     this.audioPlayTime = document.getElementById('audioPlayer').currentTime;
      //   }
      //   this.playAudioHls(this.audioAndSrc);
      // } else if (!IS_IOS && document.getElementById('audioPlayer').src == this.audioAndSrc) {
      //   this.playAudioHls(this.audioIOSSrc);
      // }
      if (IS_IOS && (document.getElementById("audioPlayer").src == this.audioIOSSrc)) {
        this.playAudioHls(this.audioUrl, '');
      } else if (!IS_IOS && ( document.getElementById("audioPlayer").src == this.audioAndSrc)) {
        this.playAudioHls(this.audioUrl, "hls");
      } else {
        this.playAudioHls(this.audioUrl);
      }
    },
    //重新开始播放
    rePlay() {
      document.getElementById('audioPlayer').load();
      this.audioPlay();
    },
    audioPlayEnd() {
      this.audioPlayTime = 0;
      this.isClickPause = false;
      clearInterval(playTimeControl);
      this.$emit("audioPlayEnd", pageStatus);
    },
    //开始播放音频
    audioCanPlay(e) {
      this.duration = Math.floor(e.target.duration);
      isFirstPlay = false;
      isCanPlay = true;
      // if (IS_IOS && this.audioPlayTime * 1 > 0) {
      //   document.getElementById('audioPlayer').currentTime = this.audioPlayTime;
      // }
      console.log("audioCanPlay------" + e.target.duration);
      setTimeout(() => {
        this.$emit('audioCanplay', this.duration);
      }, 500)
    },
    loadedmetadata(e) {
      console.log("loadedmetadata------" + e.target.duration);
    },
    audioTimeUpdate() {
      // //如果正在拖动 || 还不能播放，则不更新时间
      if (isDeactivated || !isCanPlay || this.dragFlag) {
        return;
      }
      playTimeControl = setTimeout(() => {
        if (Math.floor(document.getElementById('audioPlayer').currentTime) > 0) {
          this.audioPlayTime = Math.floor(document.getElementById('audioPlayer').currentTime);
        }
        this.$emit("onPlayTimeChange", this.audioPlayTime, this.duration);
        if (!this.hasPermission && this.watchTime && this.audioPlayTime > this.watchTime) {
          this.$emit("watchEnd");
          document.getElementById('audioPlayer').load();
          this.audioPause();
        }
      }, 200);
    },
    audioPlay(e) {
      console.log("audioPlay------");
      console.log("audioPlayTime------" + this.audioPlayTime);
      this.playStatus = 1;
      this.$emit("changePlayStatus", this.playStatus);
      if (IS_IOS && hiddenPlay == 1) {
        document.getElementById('audioPlayer').src = this.audioIOSSrc;
        document.getElementById('audioSource').src = this.audioIOSSrc;
        this.audioSrc = this.audioIOSSrc;
        hiddenPlay = 0;
      }
      document.getElementById('audioPlayer').playbackRate = this.playbackRate;
      document.getElementById('audioPlayer').play();
      // if (this.$isWxApp()) {
      //   document.getElementById('audioPlayer').playbackRate = this.playbackRate;
      //   document.getElementById('audioPlayer').play();
      // } else {
      //   if (IS_IOS) {
      //     var audioPlayer = document.createElement('audio');
      //     audioPlayer.src = this.audioUrl;
      //     document.body.appendChild(audioPlayer);
      //     this.audioPlayTime = Math.floor(audioPlayer.currentTime);
      //   } else {
      //     var audioContext = new (window.AudioContext || window.webkitAudioContext)()
      //     try {
      //       audioContext.resume()
      //       if (!audioContext) {
      //         this.$showCjToast({
      //           text: "浏览器不支持webAudioApi相关接口",
      //           type: "warn",
      //           time: 1500
      //         });
      //         return
      //       }
      //     } catch (e) {
      //       if (!audioContext) {
      //         this.$showCjToast({
      //           text: "浏览器不支持webAudioApi相关接口",
      //           type: "warn",
      //           time: 1500
      //         });
      //         return
      //       }
      //     }
      //   }
      // }

    },
    audioPause(e) {
      this.playStatus = 0;
      this.$emit("changePlayStatus", this.playStatus);
      document.getElementById('audioPlayer').pause();
      clearInterval(playTimeControl);
      console.log("audioPause------");
    },
    dragStart() {
      this.dragFlag = true;
    },
    dragging() {
      this.dragFlag = true;
      clearInterval(playTimeControl);
      console.log("dragging------");
    },
    //拖动结束，更改播放器当前时间，重新开始循环获取当前时间
    dragEnd() {
      //拖动的时间大于之前已播放的时间 && 拖动的时间大于学习记录里的进度 && 禁止拖动  则禁止拖动
      if (this.audioPlayTime > document.getElementById('audioPlayer').currentTime && this.audioPlayTime > this.totalPlayedTime && !this.isAllowProgressBar) {
        this.$showCjToast({
          text: '该课程被限制快进，请学完后再试',
          type: "text",
        });
        this.dragFlag = false;
        if (this.playStatus == 0) {
          let that = this;
          setTimeout(function () {
            that.audioPlayTime = Math.floor(document.getElementById('audioPlayer').currentTime ? document.getElementById('audioPlayer').currentTime : 0);
          }, 500)
        }
        return;
      }
      this.$emit('dragEnd')
      document.getElementById('audioPlayer').currentTime = this.audioPlayTime;
      this.dragFlag = false;
      if (!IS_IOS) {
        isCanPlay = false;
      }
      console.log("dragEnd-----------");
    },
    inputChange(value) {
      if (value > document.getElementById('audioPlayer').currentTime && value > this.totalPlayedTime && !this.isAllowProgressBar) {
        this.$showCjToast({
          text: '该课程被限制快进，请学完后再试',
          type: "text",
        });
        if (this.playStatus == 0) {
          let that = this;
          setTimeout(function () {
            that.audioPlayTime = Math.floor(document.getElementById('audioPlayer').currentTime ? document.getElementById('audioPlayer').currentTime : 0);
          }, 500)
        }
        return;
      }
      console.log("inputChange-----------");
      if (this.dragFlag) {
        this.dragFlag = false;
        return;
      }
      console.log("inputChange-----dragFlag------");
      document.getElementById('audioPlayer').currentTime = this.audioPlayTime;
    },
    listenBack() {
      this.$emit("getMiniQr");
      this.isShowMiniQr = true;
    },
    setTime(goTime) {
      document.getElementById('audioPlayer').currentTime = goTime;
    }
  },
  activated() {
    console.log("activated----");
    console.log(this.audioPlayTime);
    isDeactivated = false;
    // isPlaySuccess = 0;
    pageStatus = 'visible';
    hiddenPlay = 0;
    clearInterval(playTimeControl);
    this.isClicked = false;
    this.hasWxapp = localStorage.getItem("hasWxapp");
    this.ckFrom = this.$route.query.ckFrom;
    this.isAndroidApp = navigator.userAgent.indexOf("APPLogin") > -1; //android终端
    document.removeEventListener('visibilitychange', this.visibilitychange);
    document.addEventListener('visibilitychange', this.visibilitychange);
    document.getElementById('audioPlayer').removeEventListener('play', this.onPlay);
    document.getElementById('audioPlayer').removeEventListener('pause', this.onPause);
    document.getElementById('audioPlayer').removeEventListener('error', this.audioError);
    document.getElementById('audioPlayer').removeEventListener('timeupdate', this.audioTimeUpdate);
    document.getElementById('audioPlayer').removeEventListener('canplay', this.audioCanPlay);
    document.getElementById('audioPlayer').removeEventListener('ended', this.audioPlayEnd);
    document.getElementById('audioPlayer').addEventListener('play', this.onPlay);
    document.getElementById('audioPlayer').addEventListener('pause', this.onPause);
    document.getElementById('audioPlayer').addEventListener('error', this.audioError);
    document.getElementById('audioPlayer').addEventListener('timeupdate', this.audioTimeUpdate);
    document.getElementById('audioPlayer').addEventListener('canplay', this.audioCanPlay);
    document.getElementById('audioPlayer').addEventListener('ended', this.audioPlayEnd);
    this.isHls = "";
    this.isIosApp = utilJs.isIosAudioApp();
    this.audioType = this.isIosApp || this.isAndoridApp ? 1 : 2;
    this.isClickPause = false;
  },
  deactivated() {
    isDeactivated = true;
    document.removeEventListener('visibilitychange', this.visibilitychange);
    clearInterval(playTimeControl);
    this.playStatus = 0;
    this.audioPlayTime = 0;
    this.duration = 0;
    // this.playbackRate = 1;
    this.isNeedFirstPlay = false;
    isFirstPlay = true;
    console.log("deactivated----");
    console.log(this.audioPlayTime);
  }
};
</script>
<style scoped>
.btn-play-bg {
  background-color: #569ef8;
}
.audio-icon:active {
  color: #569ef8;
}
</style>
<style>
.videoAudio .vue-slider-dot {
  width: 20px !important;
  height: 20px !important;
  padding: 5px;
}
.mtp220 {
  margin-top: 5.5rem;
}
.qr {
  width: 65%;
  padding: 1.2rem 0.4rem;
  border-radius: 3px;
  background-color: #fff;
  margin: 0 auto;
}
.audio-auditon {
  border: solid 2px #fff;
  top: -0.15rem;
  right: -1.1rem;
  background-color: #569ef8;
}
</style>
